package by.bsuir.sn.remoting;

import by.bsuir.sn.model.Tables;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.ArrayList;
import java.util.List;

public class RemoteService
{
	public List getAll() throws Exception
	{
		Exception ex = null;
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		List<List> all = new ArrayList<List>();
		Session session = null;
		try
		{
			session = sessionFactory.openSession();
			for(Class c : Tables.getAll())
				all.add(session.createCriteria(c).list());
		}
		catch(Exception e)
		{
			e.printStackTrace();
			ex = e;
		}
		finally
		{
			if(session != null && session.isOpen())
			{
				session.close();
			}
		}
		if(ex != null)
			throw new Exception(ex.getMessage());

		return all;
	}

	public void addItem(Object item) throws Exception
	{
		Exception ex = null;
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = null;
		try
		{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.save(item);
			session.getTransaction().commit();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			ex = e;
		}
		finally
		{
			if(session != null && session.isOpen())
			{
				session.close();
			}
		}
		if(ex != null)
			throw new Exception(ex.getCause());
	}

	public void deleteItem(Object item) throws Exception
	{
		Exception ex = null;
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = null;
		try
		{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.delete(item);
			session.getTransaction().commit();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			ex = e;
		}
		finally
		{
			if(session != null && session.isOpen())
			{
				session.close();
			}
		}
		if(ex != null)
			throw new Exception(ex.getCause());
	}

	public void updateItem(Object item) throws Exception
	{
		Exception ex = null;
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		Session session = null;
		try
		{
			session = sessionFactory.openSession();
			session.beginTransaction();
			session.update(item);
			session.getTransaction().commit();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			ex = e;
		}
		finally
		{
			if(session != null && session.isOpen())
			{
				session.close();
			}
		}
		if(ex != null)
			throw new Exception(ex.getCause());
	}
}
